package com.huayue.controller;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.huayue.annotation.LogAnno;
import com.huayue.dao.AuthCodeDao;
import com.huayue.entity.AuthCode;
import com.huayue.entity.Employee;
import com.huayue.entity.User;
import com.huayue.service.EmployeeService;
import com.huayue.service.UserService;
import com.huayue.util.AuthCodeDB;
import com.huayue.util.MapToBean;

/**
 * 后台用户操作 只存放不需要登录即可被访问的路径
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService svc;

    @Autowired
    EmployeeService esvc;

    /**
     * 找回密码-获得验证码
     *
     * @param authCode
     * @return
     */
    @LogAnno(operateType = "找回密码-发送验证码")
    @RequestMapping("/sendAuthCodeByPhone")
    public ModelAndView sendAuthCodeByPhone(AuthCode authCode) {
        FastJsonJsonView view = new FastJsonJsonView();
        // 从数据库查询该电话号码是否存在
        User user = new User();
        user.setPhone(authCode.getPhone());
        Map<String, Object> map = svc.findOneByPhone(user);
        // 存在则获取短信验证码 否则直接返回
        if (map != null) {
            AuthCodeDao authCodeDao = new AuthCodeDao();
            view.addStaticAttribute("status", authCodeDao.sendAuthCode(authCode));
            view.addStaticAttribute("msg", "验证码已发送至你的手机，请注意查收");
            view.addStaticAttribute("icon", 1);
        } else {
            view.addStaticAttribute("status", false);
            view.addStaticAttribute("msg", "账号不存在");
            view.addStaticAttribute("icon", 2);
        }
        view.addStaticAttribute("code", 0);
        return new ModelAndView(view);
    }

    /**
     * 找回密码-验证验证码是否正确
     *
     * @param authCode
     * @return
     */
    @LogAnno(operateType = "找回密码-发送验证码")
    @RequestMapping("/findAuthCodeByUserInfo")
    public ModelAndView findAuthCodeByUserInfo(AuthCode authCode, HttpServletRequest request) {
        FastJsonJsonView view = new FastJsonJsonView();
        // 验证验证码信息
        if (AuthCodeDB.AUTHCODEDB.get(authCode.getPhone()) != null) {
            AuthCodeDao authCodeDao = new AuthCodeDao();
            view.addStaticAttribute("status", authCodeDao.verifyAuthCode(authCode));
            HttpSession session = request.getSession();
            session.setAttribute("phone", authCode.getPhone());
            view.addStaticAttribute("msg", "已返回验证信息");
            view.addStaticAttribute("icon", 1);
        } else {
            view.addStaticAttribute("status", false);
            view.addStaticAttribute("msg", "请先发送验证码");
            view.addStaticAttribute("icon", 2);
        }
        view.addStaticAttribute("code", 0);
        return new ModelAndView(view);
    }

    /**
     * 忘记密码，更改密码
     * 
     * @param user
     * @return
     */
    @LogAnno(operateType = "找回密码-修改密码")
    @RequestMapping("/updatePassword")
    public ModelAndView updatePassword(User user, HttpServletRequest request) {
        FastJsonJsonView view = new FastJsonJsonView();
        HttpSession session = request.getSession();
        user.setPhone(session.getAttribute("phone").toString());
        int status = svc.updatePassword(user);
        view.addStaticAttribute("code", 0);
        view.addStaticAttribute("status", status);
        if (status > 0) {
            view.addStaticAttribute("icon", 1);
            view.addStaticAttribute("msg", "密码已成功重置");
        } else {
            view.addStaticAttribute("icon", 2);
            view.addStaticAttribute("msg", "密码重置失败");
        }
        return new ModelAndView(view);
    }

    /**
     * 登录
     * 
     * @param user
     * @param request
     * @return 用户信息
     * @throws Exception
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView findPage(User user, HttpServletRequest request) throws Exception {
        FastJsonJsonView view = new FastJsonJsonView();
        if (user.getPhone() != null && user.getPassword() != null && !"".equals(user.getPhone())
            && !"".equals(user.getPassword())) {
            Map<String, Object> userDB = svc.login(user);
            User users = MapToBean.convertMap2Bean(userDB, User.class);
            view.addStaticAttribute("code", 0);
            if (userDB != null) {
                view.addStaticAttribute("status", 200);
                view.addStaticAttribute("msg", "登录成功！");
                view.addStaticAttribute("icon", 1);
                view.addStaticAttribute("data", userDB);
                request.getSession().setAttribute("USER", users);
            } else {
                view.addStaticAttribute("status", 300);
                view.addStaticAttribute("icon", 2);
                view.addStaticAttribute("msg", "登录失败，请检查手机号和密码是否正确！");
            }

        } else {
            view.addStaticAttribute("status", 400);
            view.addStaticAttribute("icon", 2);
            view.addStaticAttribute("msg", "请填写完整信息！");
        }

        return new ModelAndView(view);
    }

    /**
     * 获取session中的用户信息
     *
     * @return
     */
    @LogAnno(operateType = "登录成功")
    @RequestMapping("/findUserBySession")
    public ModelAndView findUserBySession(HttpServletRequest request, HttpServletResponse response) {
        FastJsonJsonView view = new FastJsonJsonView();
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(3600);
        User users = (User)session.getAttribute("USER");

        if (users.getRealname() == null) {
            view.addStaticAttribute("status", 300);
            return new ModelAndView(view);
        }
        Employee e = new Employee();
        e.setId(users.getId());
        Map<String, Object> temp = esvc.findOne(e);
        view.addStaticAttribute("status", 200);
        view.addStaticAttribute("userName", users.getRealname());
        view.addStaticAttribute("roleName", temp.get("rname"));
        view.addStaticAttribute("userIcon", temp.get("icon"));
        view.addStaticAttribute("userId", String.valueOf(users.getId()));
        view.addStaticAttribute("roleId", String.valueOf(users.getRole_id()));
        Cookie cookie = new Cookie("userId", String.valueOf(users.getId()));
        cookie.setPath("/");
        cookie.setDomain("localhost");
        cookie.setHttpOnly(false);
        Cookie cookie2 = new Cookie("roleId", String.valueOf(users.getRole_id()));
        cookie2.setPath("/");
        cookie2.setDomain("localhost");
        cookie2.setHttpOnly(false);
        response.addCookie(cookie);
        response.addCookie(cookie2);
        return new ModelAndView(view);
    }

    /**
     * 用户退出登录
     *
     * @return
     */
    @RequestMapping("/userExit")
    public ModelAndView userExit(HttpServletRequest request) {
        FastJsonJsonView view = new FastJsonJsonView();
        HttpSession session = request.getSession();
        Enumeration em = request.getSession().getAttributeNames();
        while (em.hasMoreElements()) {
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        view.addStaticAttribute("code", 0);
        return new ModelAndView(view);
    }

    @RequestMapping("/sendAuthCode")
    public ModelAndView sendAuthCodeByPhoneCustomer(AuthCode authCode) {
        FastJsonJsonView view = new FastJsonJsonView();
        AuthCodeDao authCodeDao = new AuthCodeDao();
        boolean flag = authCodeDao.sendAuthCode(authCode);
        if (flag) {
            view.addStaticAttribute("msg", "验证码已发送至你的手机，请注意查收");
            view.addStaticAttribute("icon", 1);
        } else {
            view.addStaticAttribute("msg", "验证码发送失败");
            view.addStaticAttribute("icon", 2);
        }
        view.addStaticAttribute("code", 0);
        return new ModelAndView(view);
    }

}
